package com.wayne.factory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工厂类，生产bean
 */
public class BeanFactory {
  private static Map<String, Object> map = new HashMap<>(); // 存储对象

  static {
    // 加载xml
    InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
    // 解析xml
    SAXReader saxReader = new SAXReader();
    try {
      Document doc = saxReader.read(resourceAsStream);
      Element root = doc.getRootElement();

      // 保存对象
      List<Element> beanList = root.selectNodes("//bean");
      for (int i = 0; i < beanList.size(); i++) {
        Element element = beanList.get(i);
        String id = element.attributeValue("id"); //
        String clazz = element.attributeValue("class");
        if (map.containsKey(id)) {
          throw new RuntimeException("已经存在bean");
        }
        Class<?> aClass = Class.forName(clazz);
        Object instance = aClass.newInstance();
        map.put(id, instance);
      }
      // 封装对象属性
      List<Element> propertyList = root.selectNodes("//property");
      for (int i = 0; i < propertyList.size(); i++) {
        Element element = propertyList.get(i);
        String name = element.attributeValue("name");
        String ref = element.attributeValue("ref");
        Element parent = element.getParent();
        String parentId = parent.attributeValue("id");
        Object parentObject = map.get(parentId);
        Method[] methods = parentObject.getClass().getMethods();
        for (Method method : methods) {
          if (method.getName().equalsIgnoreCase("set" + name)) {
            method.invoke(parentObject, map.get(ref));
          }
        }
        map.put(parentId, parentObject);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static Object getBean(String id) {
    return map.get(id);
  }
}
